﻿using jinmaMesProxy.DataAccess;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace jinmaMesProxy.Excep
{
    public class GlobalExceptions : IExceptionFilter
    {
        public GlobalExceptions()
        {
        }
        public void OnException(ExceptionContext context)
        {
            if (!(context.Exception is MyException))
            {
                return;
            }
            if (!context.ExceptionHandled)
            {
                Logger.Err(string.Format("客户端{0}访问{1}时引发了一个异常{2}",
                    context.HttpContext.Connection.RemoteIpAddress, context.HttpContext.Request.GetDisplayUrl(), ExceptionUtil.FormatExceptionInfo(context.Exception)));
                string msg = context.Exception.Message;
                var result = new ResponseData<string>()
                {
                    Data = new string[] { "操作错误" },
                    Message = msg,
                    SystemCode =-1,
                };
                if (!context.HttpContext.Response.HasStarted)
                {
                    context.HttpContext.Response.ContentType = "application/json; charset=utf-8";
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.HttpContext.Response.WriteAsync(Utils.Serialize(result));
                }
                var instance = ServiceLoader.GetService<ErpDbInstance>();
                if (instance != null) instance.Abort();
            }
        }
    }
    public class NaviteExceptions : IExceptionFilter
    {
        public NaviteExceptions()
        {
        }
        public void OnException(ExceptionContext context)
        {
            if (context.Exception is MyException)
            {
                return;
            }
            if (!context.ExceptionHandled)
            {
                Logger.Err(string.Format("客户端{0}访问{1}时引发了一个异常{2}",
                    context.HttpContext.Connection.RemoteIpAddress, context.HttpContext.Request.GetDisplayUrl(), ExceptionUtil.FormatExceptionInfo(context.Exception)));
                string msg = context.Exception.Message;
                var result = new ResponseData<string>()
                {
                    Data = new string[] { "操作错误" },
                    Message = msg,
                    SystemCode = -1,
                };
                if (!context.HttpContext.Response.HasStarted)
                {
                    context.HttpContext.Response.ContentType = "application/json; charset=utf-8";
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.HttpContext.Response.WriteAsync(Utils.Serialize(result));
                }
                var instance = ServiceLoader.GetService<ErpDbInstance>();
                if (instance != null) instance.Abort();
            }
        }
    }
}
